package com.jike.week1;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

/**
 * @program: ruletest
 * @description:
 * @author: LeoNiu
 * @create: 2021-11-08 10:49
 **/
public class HelloClassLoader extends ClassLoader {

    public static void main(String[] args) {
        HelloClassLoader classLoader = new HelloClassLoader();
        try {
            classLoader.loadClass("Hello");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
//        super.defineClass("hello",)

        try {
            byte[] classBytes = this.getClassBytes();
            Class<?> helloClass = defineClass("Hello", classBytes, 0, classBytes.length);
            Method hello = helloClass.getMethod("hello");
            Object obj = helloClass.newInstance();
            hello.invoke(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.loadClass(name);
    }

    public byte[] getClassBytes() throws IOException {
        InputStream in = HelloClassLoader.class.getResourceAsStream("/Hello.xlass");
        byte[] bytes = new byte[in.available()];

        for (int i = 4; i < bytes.length; i++) {
            bytes[i] = (byte) (255 - bytes[i]);
        }
        return bytes;
    }
}
